var roles = {
            admin: 0,
            menager: 1,
            worker: 2
        };



var ediControllers = angular.module('ediControllers', ['datatables','angular-md5']);

ediControllers.controller('LoginCtrl', function ($scope, $http, $location, $rootScope, AUTH_EVENTS, AuthService, md5){

        $scope.user = {};
        $scope.user.username = '';
        $scope.user.passwordHash = '';
        
        $scope.loginUser = {
                userId : '',
                userFirstName : '',
                userLastName : '',
                userLogin : '',
                userDepId : ''
        };

        $scope.loginUser = function(user) {
            user.passwordHash = md5.createHash(user.passwordHash);
            $scope.resetError();
            $http.post('login/authenticate', user)
                .success(function(login) {                       

                    $scope.user.username = '';
                    $scope.user.passwordHash = '';  
                    
                    AuthService.login(login);

                    if(login.errorCode === 0){
                        $rootScope.userId = login.userId;
                        $rootScope.firstName = login.firstName;
                        $rootScope.lastName = login.lastName;
                        $rootScope.login = login.login;
                        $rootScope.depId = login.depId;
                        $location.path('/table/1');
                    } else {
                            $scope.setError('Błędny email lub hasło');
                    }

                })
                .error(function() {
                    $scope.setError('Coś poszło nie tak');
                });
        };

        $scope.resetError = function() {
            $scope.error = false;
            $scope.errorMessage = '';
        };

        $scope.setError = function(message) {
            $scope.error = true;
            $scope.errorMessage = message;
            $rootScope.SessionId='';
        };
});

ediControllers.controller('MainCtrl', function( $scope, $http, $routeParams, $location, AuthService, FileOperation, MessageFactory, DTInstances) {
    var vm = this;
    
    DTInstances.getLast().then(function (dtInstance) {
        vm.dtInstance = dtInstance;
    });
    //vm.refreshTable = refreshTable;
    
    $scope.catId = $routeParams.catId;
    vm.files;
    $scope.deps;
    $scope.workers;

        $scope.dtInstance ;
    
        $scope.passFileData = {
		departmentID: '',
		userID: '',
                comment: ''
	};
    
	$scope.currentUser = {
		email: AuthService.user().firstName+' '+AuthService.user().lastName,
                userId:AuthService.user().userId,
                depId:AuthService.user().depId,
	};
        //DONE
        $scope.setFile = function(id){
            $('.file_input').val(id);
        }
	//DONE
	$scope.blockFile = function(id){
		FileOperation.blockFile(id);
	}
	//DONE
	$scope.unblockFile = function(id){
		FileOperation.unblockFile(id);
	}
        
	$scope.returnFile = function(id){
		FileOperation.returnFile(id);
	}
        
        $scope.showModal = function(id){
            $('.file_input').val(id);
            $scope.getDepartments();
            $scope.getWorkers();
        }
        
        $scope.showFileHistory = function(id){
            FileOperation.getHistory(id);
        }
        //DONE
	$scope.moveFile = function(passFileData){
           // if(passFileData.departmentID == ''){
                //MessageFactory.errorMoveFileMsg('Departament musi zostać wybrany.');
           /*}else*/ if(passFileData.comment == ''){
                MessageFactory.errorMoveFileMsg('Musisz skomentować swoje zmiany.');
            }else{
		FileOperation.moveFile(passFileData);
            }
	}
	//DONE
	$scope.closeFile = function(id){
		FileOperation.closeFile(id);
	}
        
        $scope.goToUpload = function(id){
                $location.path('/upload/'+id);
        }   
        
        $scope.removeFile = function(id){
            FileOperation.removeFile(id);
        }
	
	$scope.logout = function () {
		AuthService.logout();
	};
        
        $scope.getDepartments = function (){
            $http({
                method: 'GET',
                url: 'department/getDepartments'
            }).success(function(data){
                $scope.deps = data.departments;
            }).error(function(){
                    alert("wystapił błąd podczas pobierania departamentów.");
            });
        }
        
        $scope.getWorkers = function (){
            $http({
                method: 'GET',
                url: 'employee/getEmployees'
            }).success(function(data){
                $scope.workers = data.employees;
            }).error(function(){
                    alert("wystapił błąd podczas pobierania pracowników.");
            });
        }
        
        $scope.refreshTable = function () {
            //console.log('refres');
            //vm.files = FileOperation.getFiles2();
            $http({
                method: 'POST',
                url: 'document/documentList',
                data: '{"userId": "'+AuthService.user().userId+'" }',
                headers: {'Content-Type': 'application/json'}
            }).success(function(data){
                vm.files = data.documents;
               
            }).error(function(){
                    alert("wystapił błąd podczas pobierania plików.");
            });
        };
        
        $scope.refreshTable();
        $scope.getDepartments();
});

ediControllers.controller('UploadCtrl', function($scope, $location, $http, $routeParams, AuthService) {
    $scope.fileId = $routeParams.fileId;

	$scope.currentUser = {
		email: AuthService.user().login
	};
	
	$scope.logout = function () {
		AuthService.logout();
	};
        
        $scope.goToTable = function(){
                $location.path('/table/1');
        } 
        
        
        
        $scope.showHistory = function (id){
            
        };
 
        $scope.document = {};
        $scope.document.title = '';
        $scope.document.fileInput = '';
        $scope.document.isFinalCheck = '';
        $scope.document.isFinal = 0;
        var fileExtension = '';

        $scope.setExtension = function(fileInput) {

            var file = fileInput.value;
//            var filename = file.replace(/^.*[\\\/]/, '');
            fileExtension = file.split('.').pop();
//            var title = filename.substr(0, filename.lastIndexOf('.'));
//            $("#title").val(title);
//            $("#title").focus();
//            $scope.document.title=title;
//            
//            console.log($scope.document);
        };
        $scope.uploadFile=function(){
            console.log(file.files[0]);
            console.log(fileExtension);
            console.log(AuthService.user().userId);
            if($scope.document.isFinalCheck === true) {
                $scope.document.isFinal = 1;
            }
            else if($scope.document.isFinalCheck === false) {
                $scope.document.isFinal = 0;
            }
            else {
                $scope.document.isFinal = 0;
            }
            console.log($scope.document.isFinal);
            
            var formData=new FormData();
            formData.append("file",file.files[0]);
            formData.append("userId", AuthService.user().userId);
            formData.append("extension", fileExtension);
            formData.append("isFinal", $scope.document.isFinal);
            $http({
                method: 'POST',
                url: 'document/uploadFile',
                headers: { 'Content-Type': undefined},
                data:  formData,
                transformRequest: angular.identity
             })  
             .success(function(data, status) {                       
                 alert("Plik został zapisany");
                 $scope.goToTable();
             })
             .error(function(data, status) {
                 alert("Wystąpił błąd podczas zapisu");
             });
        };
        
});

ediControllers.factory('MessageFactory', function() {
	var messageFactory = {};
	
	messageFactory.successMsg = function(){
		$('.mainRow').prepend(
			'<div class="alert alert-success">'+
				'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
				'Operacja zakończona pomyślnie.'+
			'</div>');
	};
	
	messageFactory.errorMsg = function(){
		$('.mainRow').prepend(
			'<div class="alert alert-danger">'+
				'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
				'Wystąpił błąd. Operacja nie zakończona.'+
			'</div>');
	};
        
        messageFactory.errorMoveFileMsg = function(text){
            if(text == ''){text = 'Wystąpił błąd. Operacja nie zakończona.';}
		$('.moveFileMainRow').prepend(
			'<div class="alert alert-danger text-left">'+
				'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
				text+
			'</div>');
	};
	
	return messageFactory;
});
 
ediControllers.factory('FileOperation', function($http, AuthService, MessageFactory) {
	var fileOperation = {};
	
	//blokowanie pliku
	fileOperation.blockFile = function (id){
                $.ajax({
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    type: 'POST',
                    url: 'document/lock',
                    data:'{"fileId": "'+id+'", "userId": "'+AuthService.user().userId+'" }',
                    dataType: 'json',
                    success:function(data){
                        if(data.errorCode == 0){
                            MessageFactory.successMsg();
                        }else{
                            MessageFactory.errorMsg();
                        }
                      },
                    error: function(data) { // if error occured
                        MessageFactory.errorMsg();
                    },
                });
        };
        //usuwanie pliku
	fileOperation.removeFile = function (id){
                $.ajax({
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    type: 'POST',
                    url: 'document/archiveFile',
                    data:'{"documentId": "'+id+'", "userId": "'+AuthService.user().userId+'" }',
                    dataType: 'json',
                    success:function(data){
                        if(data.errorCode == 0){
                            MessageFactory.successMsg();
                        }else{
                            MessageFactory.errorMsg();
                        }
                      },
                    error: function(data) { // if error occured
                        MessageFactory.errorMsg();
                    },
                });
        };
	//odblokowanie pliku
	fileOperation.unblockFile = function (id){
		$.ajax({
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    type: 'POST',
                    url: 'document/unlock',
                    data:'{"fileId": "'+id+'", "userId": "'+AuthService.user().userId+'" }',
                    dataType: 'json',
                    success:function(data){
                        if(data.errorCode == 0){
                            MessageFactory.successMsg();
                        }else{
                            MessageFactory.errorMsg();
                        }
                      },
                    error: function(data) { // if error occured
                        MessageFactory.errorMsg();
                    },
                });
	};
        
        //pobranie pliku
	fileOperation.downloadFile = function (id){
                $.ajax({
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    type: 'POST',
                    url: 'document/lock',
                    data:'{"fileId": "'+id+'", "userId": "'+AuthService.user().userId+'" }',
                    dataType: 'json',
                    success:function(data){
                        if(data.errorCode == 0){
                            MessageFactory.successMsg();
                        }else{
                            MessageFactory.errorMsg();
                        }
                      },
                    error: function(data) { // if error occured
                        MessageFactory.errorMsg();
                    },
                });
        };
	//zamkniecie pliku
	fileOperation.closeFile = function (id){
		console.log('zamknij');
                
                $.ajax({
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    type: 'POST',
                    url: 'document/markFinal',
                    data:'{"fileId": "'+id+'", "userId": "'+AuthService.user().userId+'" }',
                    dataType: 'json',
                    success:function(data){
                        if(data.errorCode == 0){
                            MessageFactory.successMsg();
                        }else{
                            MessageFactory.errorMsg();
                        }
                      },
                    error: function(data) { // if error occured
                        MessageFactory.errorMsg();
                    },
                });
	};
	
	//przekazanie pliku
	fileOperation.moveFile = function (passFileData){
		console.log('przekaż');
                $.ajax({
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    type: 'POST',
                    url: 'document/passFile',
                    data:'{"fileId": "'+$('.file_input').val()+'", "userId": "'+ passFileData.userID +'", "auditUsrId": "'+AuthService.user().userId+'", "departmentId": "'+ passFileData.departmentID +'", "comment": "'+ passFileData.comment +'"}',
                    dataType: 'json',
                    success:function(data){
                        if(data.errorCode == 0){
                            MessageFactory.successMsg();
                        }else{
                            MessageFactory.errorMsg();
                        }
                        $('.file_move').hide();
                        $('.modal-backdrop').remove();
                      },
                    error: function(data) { // if error occured
                        MessageFactory.errorMsg();
                    },
                });
	};
	
	//zwrocenie pliku
	fileOperation.returnFile = function (id){
		console.log('zwroc');
	};
        
        fileOperation.getFiles = function (){
           return [{
                "id": 1,
                "name": "Plik 1",
                "status": "Zablokowany",
                "dateMod": "2014-12-01 12:00"
            }, {
                "id": 2,
                "name": "Plik 2",
                "status": "Wolny",
                "dateMod": "2014-12-01 12:00"
            }];
        };
        
        fileOperation.getFiles2 = function (){
           return [{
                "id": 3,
                "name": "Plik 3",
                "status": "Zablokowany",
                "dateMod": "2014-12-01 12:00"
            },{
                "id": 4,
                "name": "Plik 4",
                "status": "Zablokowany",
                "dateMod": "2014-12-01 12:00"
            }];
        };
        
        //przekazanie pliku
	fileOperation.getHistory= function (id){
            console.log('historia');
                $.ajax({
                    headers: { 
                        'Accept': 'application/json',
                        'Content-Type': 'application/json' 
                    },
                    type: 'POST',
                    url: 'document/showHistory',
                    data:'{"fileId": "'+id+'"}',
                    dataType: 'json',
                    success:function(data){
                        if(data.errorCode == 0){
                            $('.file_history .modal-body').html('');
                            //console.log(data.history.length);
                            if(data.history.length == 0){
                                $('.file_history .modal-body').prepend('brak historii pliku');
                            }else{
                                for (var i = 0; i < data.history.length; i++) {
                                    //console.log(data.history[i]);
                                    $('.file_history .modal-body').prepend(
                                        '<blockquote>'+
                                            '<h3>Modyfikacja przez '+data.history[i].lastModifiedBy+'<small class="pull-right">Data operacji:'+data.history[i].lastModifiedDate.year+'-'+data.history[i].lastModifiedDate.monthOfYear+'-'+data.history[i].lastModifiedDate.dayOfYear+' '+data.history[i].lastModifiedDate.hourOfDay+':'+data.history[i].lastModifiedDate.minuteOfHour+'</small></h3>'+
                                            '<p>'+data.history[i].dchComment+'</p>'+
                                        '</blockquote>');
                                }
                            }
                            //MessageFactory.successMsg();
                        }else{
                            MessageFactory.errorMsg();
                            $('.file_history').hide();
                            $('.modal-backdrop').remove();
                        }
                      },
                    error: function(data) { // if error occured
                        MessageFactory.errorMsg();
                    },
                });
	};
	
	return fileOperation;
});
  
ediControllers.factory('AuthService', function ($http, Session) {
	var authService = {};
 
	authService.login = function (loggedUser) { 
		Session.create(1, loggedUser.userId, loggedUser.firstName, loggedUser.lastName, loggedUser.login, loggedUser.depId );
		return loggedUser;
	};
	
	authService.logout = function () {
		Session.destroy();
	}
 
	authService.isAuthenticated = function () {
		return !!Session.userId;
	};
	
	authService.user = function () {
		return Session;
	}
 
	authService.isAuthorized = function (authorizedRoles) {
		if (!angular.isArray(authorizedRoles)) {
			authorizedRoles = [authorizedRoles];
		}
		return (authService.isAuthenticated() && authorizedRoles.indexOf(Session.userRole) !== -1);
	};
 
	return authService;
});
  
ediControllers.constant('AUTH_EVENTS', {
	loginSuccess: 'auth-login-success',
	loginFailed: 'auth-login-failed',
	logoutSuccess: 'auth-logout-success',
	sessionTimeout: 'auth-session-timeout',
	notAuthenticated: 'auth-not-authenticated',
	notAuthorized: 'auth-not-authorized'
});

ediControllers.service('Session', function () {
	this.create = function (sessionId, userId, userFirstName, userLastName, userLogin, userDepId) {
		this.id = sessionId;
		this.userId = userId;
		this.firstName = userFirstName;
		this.lastName = userLastName;
		this.login = userLogin;
		this.depId = userDepId;
	};
	
	this.destroy = function () {
		this.id = null;
		this.userId = null;
		this.firstName = null;
		this.lastName = null;
		this.login = null;
		this.depId = null;
	};
	
	return this;
});

ediControllers.constant('USER_ROLES', {
	all: '*',
	admin: 'admin',
	editor: 'editor',
	guest: 'guest'
})
